package com.example.backgroundmanger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.util.unit.DataSize;

import jakarta.servlet.MultipartConfigElement;
import org.springframework.beans.factory.annotation.Value;
import java.io.File;

@Configuration
public class FileUploadConfig {

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 设置文件大小限制，超出设置页面会抛出异常信息
        factory.setMaxFileSize(DataSize.ofMegabytes(5)); // 限制上传文件大小为5MB
        factory.setMaxRequestSize(DataSize.ofMegabytes(10)); // 设置总上传数据总大小
        return factory.createMultipartConfig();
    }

    @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }

    public void init() {
        try {
            String avatarDir = uploadDir + "/avatar";
            File dir = new File(avatarDir);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (created) {
                    System.out.println("创建目录成功: " + avatarDir);
                } else {
                    System.out.println("创建目录失败: " + avatarDir);
                }
            } else {
                System.out.println("目录已存在: " + avatarDir);
            }
            System.out.println("上传目录: " + uploadDir);
            System.out.println("头像目录: " + avatarDir);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Value("${file.upload-dir}")
    private String uploadDir;
} 